package com.xingfudazi.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

import java.lang.reflect.Type;
import java.util.List;

public class JSONUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static <T> T toBean(String jsonString, Class<T> beanClass) {
        try {
            return objectMapper.readValue(jsonString, beanClass);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    public static <T> List<T> toList(String jsonString, Class<T> beanClass) {
        try {
            return objectMapper.readValue(jsonString, new TypeReference<List<T>>() {
                @Override
                public Type getType() {
                    return ParameterizedTypeImpl.make(List.class, new Type[]{beanClass}, null);
                }
            });
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    public static String toJsonStr(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
